package com.yhos.platform.oopston.service.biz;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yhos.platform.oopston.base.config.OopstonConfig;
import com.yhos.platform.oopston.base.constants.CommonConstants;
import com.yhos.platform.oopston.base.enums.ShippingMethodEnum;
import com.yhos.platform.oopston.base.enums.YesNoEnum;
import com.yhos.platform.oopston.core.exception.BusinessException;
import com.yhos.platform.oopston.core.mybatis.CommonMapper;
import com.yhos.platform.oopston.core.mybatis.SnowFlake;
import com.yhos.platform.oopston.core.utils.ListUtils;
import com.yhos.platform.oopston.core.utils.MapperUtils;
import com.yhos.platform.oopston.core.utils.WebUtil;
import com.yhos.platform.oopston.mapper.entity.*;
import com.yhos.platform.oopston.mapper.mapper.*;
import com.yhos.platform.oopston.mapper.model.oopston.OrderCreateRequestApiModel;
import com.yhos.platform.oopston.mapper.model.oopston.OrderCreateResponseApiModel;
import com.yhos.platform.oopston.mapper.model.zhongtong.ZhongTongGetNewLabelRemoteResponse;
import com.yhos.platform.oopston.mapper.model.zhongtong.ZhongTongOrderCreateRemoteResponse;
import com.yhos.platform.oopston.mapper.model.zhongtong.ZhongTongOrderCreateRequestApiModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by Administrator on 2020/4/19.
 */
@Service
public class OrderLabelBiz {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OopstonConfig oopstonConfig;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private OopstonOrderMapper oopstonOrderMapper;

    @Autowired
    private ShunfengOrderTrackingInfoMapper trackingInfoMapper;

    @Autowired
    private OopstonOrderLabelItemMapper oopstonOrderLabelItemMapper;

    @Autowired
    private OopstonOrderPkgItemMapper oopstonOrderPkgItemMapper;

    @Autowired
    private OopstonOrderSkuItemMapper oopstonOrderSkuItemMapper;

    @Autowired
    private OopstonOrderExtraServiceMapper oopstonOrderExtraServiceMapper;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public OopstonOrder createOrderInfo(OrderCreateRequestApiModel requestApiModel){
        OopstonOrder order = MapperUtils.mapper(requestApiModel, OopstonOrder.class);
        order.setId(SnowFlake.getInstance().nextId());
        order.setOrderRefNo(requestApiModel.getReferenceNo());
        order.setOrderStatus(CommonConstants.BYTE_THREE);
        order.setStoreId(requestApiModel.getWarehouseId());
        order.setTotalQuantity(requestApiModel.getQuantity());
        if (requestApiModel.getQuantity() > 1) {
            order.setBaseChannelInfoId(oopstonConfig.getBigPackChannelId());
        } else {
            order.setBaseChannelInfoId(oopstonConfig.getSmallPackChannelId());
        }
        commonMapper.setBaseEntityAdd(order, CommonConstants.LONG_ZERO);

        List<OopstonOrderPkgItem> orderPackages = MapperUtils.mapper(requestApiModel.getOrderPackages(), OopstonOrderPkgItem.class);
        BigDecimal orderTotalWeight = BigDecimal.ZERO;
        if (ListUtils.isNotEmpty(orderPackages)) {
            for (OopstonOrderPkgItem orderPackage : orderPackages) {
                orderTotalWeight = orderTotalWeight.add(orderPackage.getWeight());
                orderPackage.setId(SnowFlake.getInstance().nextId());
                orderPackage.setOrderId(order.getId());
                commonMapper.setBaseEntityAdd(orderPackage, CommonConstants.LONG_ZERO);
                oopstonOrderPkgItemMapper.insert(orderPackage);
            }
        }

        List<OopstonOrderSkuItem> orderProducts = MapperUtils.mapper(requestApiModel.getOrderProducts(), OopstonOrderSkuItem.class);
        if (ListUtils.isNotEmpty(orderProducts)) {
            for (OopstonOrderSkuItem orderProduct : orderProducts) {
                orderProduct.setId(SnowFlake.getInstance().nextId());
                orderProduct.setOrderId(order.getId());
                commonMapper.setBaseEntityAdd(orderProduct, CommonConstants.LONG_ZERO);
                oopstonOrderSkuItemMapper.insert(orderProduct);
            }
        }

        order.setTotalWeight(orderTotalWeight);
        oopstonOrderMapper.insert(order);
        return order;
    }

    /**
     * 更新回填信息
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateResponse(Long orderId, OrderCreateResponseApiModel responseApiModel) {
        OopstonOrder order = new OopstonOrder();
        order.setId(orderId);
        order.setResponseOrderId(responseApiModel.getOrderId());
        order.setResponseOrderNo(responseApiModel.getOrderNo());
        order.setResponseTrackNumber(responseApiModel.getTrackNumber());
        order.setResponsePrintUrl(responseApiModel.getPrintUrl());
        if (StringUtils.isNotBlank(responseApiModel.getPrintUrl())) {
            responseApiModel.setPrintUrl(WebUtil.getFile(responseApiModel.getPrintUrl()));
        }
        order.setResponseEstimatePrice(responseApiModel.getEstimatePrice()!=null?new BigDecimal(responseApiModel.getEstimatePrice()):null);
        commonMapper.setBaseEntityModify(order,CommonConstants.LONG_ZERO);
        oopstonOrderMapper.updateById(order);

        responseApiModel.setPrintUrl("http://yhos.john-logistics.com" + responseApiModel.getPrintUrl());

        List<OopstonOrderLabelItem> labels = MapperUtils.mapper(responseApiModel.getLabels(), OopstonOrderLabelItem.class);
        if(ListUtils.isNotEmpty(labels)){
            for(OopstonOrderLabelItem label : labels){
                label.setId(SnowFlake.getInstance().nextId());
                label.setOrderId(orderId);
                commonMapper.setBaseEntityAdd(label,CommonConstants.LONG_ONE);
                oopstonOrderLabelItemMapper.insert(label);
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public OopstonOrder createZhongTongOrderInfo(ZhongTongOrderCreateRequestApiModel requestApiModel){
        OopstonOrder order = MapperUtils.mapper(requestApiModel, OopstonOrder.class);
        order.setId(SnowFlake.getInstance().nextId());
        order.setOrderRefNo(requestApiModel.getReferenceNo());
        order.setTotalQuantity(requestApiModel.getQuantity());
        order.setTotalWeight(requestApiModel.getWeight());
        if (requestApiModel.getQuantity() > 1) {
            order.setBaseChannelInfoId(oopstonConfig.getBigPackChannelId());
        } else {
            order.setBaseChannelInfoId(oopstonConfig.getSmallPackChannelId());
        }
        String shippingMethod = ShippingMethodEnum.getValueByKey(requestApiModel.getShippingMethod());
        if(StringUtils.isBlank(shippingMethod)){
            throw new BusinessException("运输方式输入有误");
        }
        commonMapper.setBaseEntityAdd(order, CommonConstants.LONG_ZERO);
        oopstonOrderMapper.insert(order);

        List<OopstonOrderSkuItem> orderProducts = MapperUtils.mapper(requestApiModel.getOrderProducts(), OopstonOrderSkuItem.class);
        if (ListUtils.isNotEmpty(orderProducts)) {
            for (OopstonOrderSkuItem orderProduct : orderProducts) {
                orderProduct.setId(SnowFlake.getInstance().nextId());
                orderProduct.setOrderId(order.getId());
                commonMapper.setBaseEntityAdd(orderProduct, CommonConstants.LONG_ZERO);
                oopstonOrderSkuItemMapper.insert(orderProduct);
            }
        }

        List<OopstonOrderExtraService> orderExtraServices = MapperUtils.mapper(requestApiModel.getExtraServices(), OopstonOrderExtraService.class);
        if (ListUtils.isNotEmpty(orderExtraServices)) {
            for (OopstonOrderExtraService orderExtraService : orderExtraServices) {
                orderExtraService.setId(SnowFlake.getInstance().nextId());
                orderExtraService.setOrderId(order.getId());
                commonMapper.setBaseEntityAdd(orderExtraService, CommonConstants.LONG_ZERO);
                oopstonOrderExtraServiceMapper.insert(orderExtraService);
            }
        }
        return order;
    }

    /**
     * 更新回填信息
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateZhongTongResponse(Long orderId, ZhongTongOrderCreateRemoteResponse responseApiModel) {
        OopstonOrder order = new OopstonOrder();
        order.setId(orderId);
        order.setResponseOrderId(responseApiModel.getData().getOrder_id());
        order.setResponseTrackNumber(responseApiModel.getData().getShipping_method_no());
        commonMapper.setBaseEntityModify(order,CommonConstants.LONG_ZERO);
        oopstonOrderMapper.updateById(order);
    }

    /**
     * 更新回填信息
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateZhongTongTrackStatus(Long orderId) {
        OopstonOrder order = new OopstonOrder();
        order.setId(orderId);
        order.setOrderStatus((byte) 1);
        oopstonOrderMapper.updateById(order);
    }

    /**
     * 更新回填信息
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateTrackStatus(Long trackId) {
        ShunfengOrderTrackingInfo trackingInfo = new ShunfengOrderTrackingInfo();
        trackingInfo.setId(trackId);
        trackingInfo.setIsSend(1);
        trackingInfoMapper.updateById(trackingInfo);
    }

    /**
     * Trancking info input into database
     */

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Boolean saveTrackInfo(ShunfengOrderTrackingInfo trackingInfo) {
        ShunfengOrderTrackingInfo trackingInfoNew = new ShunfengOrderTrackingInfo();

        //Integer trackingInfoMapper.trackingInfoMapper.selectCount();

        List<ShunfengOrderTrackingInfo> trackingList = trackingInfoMapper.selectList(new EntityWrapper<ShunfengOrderTrackingInfo>()
                .eq("tracking_no", trackingInfo.getTrackingNo())
                .eq("send_time",trackingInfo.getSendTime())
                .isNotNull("order_id"));

        if (ListUtils.isNotEmpty(trackingList)) {
            return Boolean.TRUE;
        }

        commonMapper.setBaseEntityAdd(trackingInfoNew, CommonConstants.LONG_ZERO);
        trackingInfoNew.setId(SnowFlake.getInstance().nextId());
        trackingInfoNew.setIsSend(0);
        trackingInfoNew.setMessage(trackingInfo.getMessage());
        trackingInfoNew.setTrackingNo(trackingInfo.getTrackingNo());
        trackingInfoNew.setTotalWeight(trackingInfo.getTotalWeight());
        trackingInfoNew.setOrderId(trackingInfo.getOrderId());
        trackingInfoNew.setSendTime(trackingInfo.getSendTime());
        trackingInfoMapper.insert(trackingInfoNew);
        return Boolean.TRUE;
    }


    /**
     * 更新回填信息
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateZhongTongGetTagResponse(Long orderId, ZhongTongGetNewLabelRemoteResponse responseApiModel) {
        OopstonOrder order = new OopstonOrder();
        order.setId(orderId);
        if(ListUtils.isNotEmpty(responseApiModel.getData())){
            order.setResponsePrintUrl(responseApiModel.getData().get(0).getLableFile());
            commonMapper.setBaseEntityModify(order,CommonConstants.LONG_ZERO);
            oopstonOrderMapper.updateById(order);
        }
    }
}
